<?php

	if(!defined('YMT')) exit;

	/**
	 * @package Yomm
	 * @author bsuter
	 *
	 */
	Class Yomm_Error extends Exception {
		
		public function __construct($message, $code = 0)
		{
			if(!is_string($message))
				$message = print_r($message, true);
			
			parent::__construct($message, $code);
			
			$this->sendToDb();
			
			$this->sendToApi();
		}
		
		private function sendToDb()
		{
			$db = Yomm_Db_Query::getInstance();
			
			// it could haben that the database connection is not set yet, because of outside of mainframework errors
			$db->connect(SiteConfig::SqlHost, SiteConfig::SqlUser, SiteConfig::SqlPass, SiteConfig::SqlDatabase);
			
			$logs = $db->handler("cms_error", array(
				"date" => date("Y-m-d H:i:s"), ///datetime : YYYY-MM-DD HH:MM:SS
				"session" => addslashes(print_r($_SESSION, true)),
				"post" => addslashes(print_r($_POST, true)),
				"get" => addslashes(print_r($_GET, true)),
				"debug" => addslashes('message: ' . $this->message.'; line:' . $this->line. '; file:' . $this->file),
				"object" => addslashes(trim(print_r($this->message, true)))
			));
		}
		
		private function sendToAPI()
		{
			if(!defined('SiteConfig::SendErrors')) // throw initial error
			{
				echo "SiteConfig::SendErrors not defined!";
				return false;
			}
			
			if(defined('SiteConfig::SendErrors'))
			{
				if(SiteConfig::SendErrors === true)
				{
					$txt = addslashes("{$this->message}\n\rline: {$this->line}\n\rfile: {$this->file}");
					$api_error = new Yomm_ErrorApi($txt);
				}
			}
		}
		
		/**
		 * make printable errors to display on catch.
		 */
		public function printError()
		{
			$err = "Yomm Error Detected:<br />in file <strong>{$this->getFile()}</strong> on line <strong>{$this->getLine()}</strong>: " . $this->getMessage();
			$err.= "<pre>" . print_r($this, true). "</pre>";
			return $err;
		}
		
	}